import React, { forwardRef, useImperativeHandle, useRef } from 'react';

const HYInput = forwardRef((props, ref) => {

    const inputRef = useRef();

    useImperativeHandle(ref, () => ({
        focus: () => {
            // console.log('useImperativeHandle中回调函数返回的对象focus');
            // 不希望子组件暴露给父元素过多的东西
            inputRef.current.focus();
        }
    }))

    return <input ref={inputRef} type="text" />
})

export default function UseImperativeHandleHookDemo() {
    const inputRef = useRef();

    return (
        <div>

            <HYInput ref={inputRef}/>
            <button onClick={e => inputRef.current.focus()}>聚焦</button>
        </div>
    )
}